package com.mc.lp.security.user;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import com.mc.lp.view.constants.IConstants;
/**	@author: deepak.verma
 * 	@description: simple class to decide redirected page after successful login
 * */
public class LoginUserRedirectStrategy extends AbstractRedirectStrategy implements IConstants{
	
	@Override
	public void sendRedirect(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
		super.sendRedirect(request, response, determineTargetUrl(authentication));
	}

	protected String determineTargetUrl(Authentication authentication) {
        boolean isUser = false;
        boolean isAdmin = false;
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                isUser = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            }
        }
        if (isAdmin) {
            return PAGES.ADMIN_DASHBOARD;
        } else if (isUser) {
            return PAGES.USER_WELCOME;
        } else {
            throw new IllegalStateException();
        }
    }
}
